package shayu.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import dm.jdbc.util.StringUtil;
import io.renren.common.constant.ProductConstant;
import io.renren.common.to.SkuReductionTo;
import io.renren.common.to.SpuBoundTo;
import io.renren.common.to.es.SkuEsModel;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.utils.R;
import io.seata.spring.annotation.GlobalTransactional;
import javafx.geometry.Bounds;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.record.DVALRecord;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import shayu.product.dao.SpuInfoDao;
import shayu.product.entity.*;
import shayu.product.feign.CouponFeignService;
import shayu.product.feign.SearchFeignService;
import shayu.product.feign.WareFeignService;
import shayu.product.service.*;
import shayu.product.vo.*;

import javax.xml.crypto.Data;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    //TODO 未
    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService imagesService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private ProductAttrValueService attrValueService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private SearchFeignService searchFeignService;

    @Autowired
    private AttrService attrService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        // 1.保存基本信息
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);

        // 2.保存SPU的描述图片 pms_spu_info_desc
        List<String> decript = spuSaveVo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        this.savaSpuInfoDesc(spuInfoDescEntity);

        // 3.保存图片
        List<String> images = spuSaveVo.getImages();

        imagesService.saveImages(spuInfoEntity.getId(), images);


        // 4.保存spu的规则参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(attr.getAttrId());
            productAttrValueEntity.setAttrName("");
            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        this.saveProductAttr(collect);

        // 5.1保存当前spu对应的所有sku信息
        // 5.1 sku的基本信息，pms_sku_info
        List<Skus> skus = spuSaveVo.getSkus();
        if (skus != null || skus.size() > 0) {
            skus.forEach(attr -> {
                String defaultImg = "";
                for (Images image : attr.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(attr, skuInfoEntity);
                skuInfoEntity.setBrandId(skuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(skuInfoEntity.getCatalogId());
                skuInfoEntity.setSpuId(skuInfoEntity.getSpuId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.saveSkuInfo(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();

                // 5.2 sku图片信息
                List<SkuImagesEntity> imagesEntities = attr.getImages().stream().map(item -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(item.getImgUrl());
                    skuImagesEntity.setDefaultImg(item.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entities -> {
                    // 如果true 就是需要，false就是需要剔除
                    return !StringUtils.isEmpty(entities.getImgUrl());
                }).collect(Collectors.toList());
                // 5.3 sku 销售属性信息
                skuSaleAttrValueService.saveBatch(imagesEntities);

                // TODO 没有图片的路劲需要保存

                // 5.4 sku优惠,满减等信息
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(attr, skuReductionTo);
                skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
                    R r1 = couponFeignService.savaSkuReduction(skuReductionTo);
                    if (r1.getCode() != 0) {
                        log.error("远程保存调用失败");
                    }
                }
            });
        }

//        // 6 保存积分信息
//        new SkuReductionTo().var
//        BeanUtils.copyProperties(bounds,spuBoundTo);
//        spuBoundTo.setSpuId(spuInfoDescEntity.getSpuId());
//        couponFeignService.saveSpuBounds(spuBoundTo);

    }

    @Override
    public void saveProductAttr(List<ProductAttrValueEntity> collect) {
        productAttrValueService.saveProductAttr(collect);
    }

    @Override
    public void savaSpuInfoDesc(SpuInfoDescEntity descEntity) {
        spuInfoDescService.saveSpuInfoDesc(descEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((w) -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }

        String status = (String) params.get("status");
        if (!StringUtils.isEmpty("status")) {
            wrapper.eq("publish_status", status);
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtil.isEmpty("brandId")) {
            wrapper.eq("brand_Id", brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtil.isEmpty("catelogId")) {
            wrapper.eq("catelogId", catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params)
                , wrapper);
        return new PageUtils(page);
    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public void up(Long spuId) {
        // 1.查出当前spuid对应的所有spu信息
        List<SkuInfoEntity> skus = skuInfoService.getSkuBySpuId(spuId);
        List<Long> skuIdList = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        // TODO 4. 查询当前sku的所有可以用来被检索的规格属性
        List<ProductAttrValueEntity> entities = attrValueService.baseAttrlistforspu(spuId);
        List<Long> collect = entities.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        List<Long> searchAttrIds = attrService.selectSearchAttrIds(collect);
        HashSet<Long> idSet = new HashSet<>();
        List<SkuEsModel.Attrs> attrsList = entities.stream().filter((item) -> {
            return idSet.contains(item.getAttrId());
        }).map((item) -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs);
            return attrs;
        }).collect(Collectors.toList());


        // 组装需要的数据
        SkuEsModel skuEsModel = new SkuEsModel();
        BeanUtils.copyProperties(skuEsModel, spuId);

        // TODO 1.发送远程调用，库存系统是否有库存
        R skusHasStock = wareFeignService.getSkusHasStock(skuIdList);
        Map<Long, List<Long>> stockMap = null;
        try {
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {
            };
            stockMap = skusHasStock.getData(typeReference).stream().
                    collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        } catch (Exception e) {
            e.printStackTrace();
        }

        skuEsModel.setHotScore(0L);

        // 2. 封装每个sku的信息
        Map<Long, Boolean> finalStock = null;
        List<SkuEsModel> upProducts = skus.stream().map((sku) -> {
            // 需要组装的数据
            SkuEsModel esmode1 = new SkuEsModel();
            BeanUtils.copyProperties(sku, esmode1);
            // skuImegs
            esmode1.setSkuImg(sku.getSkuDefaultImg());
            esmode1.setSkuPrice(sku.getPrice());

            if (finalStock == null) {
                esmode1.setHasStock(true);
            } else {
                esmode1.setHasStock(finalStock.get(sku.getSkuId()));
            }
            // 设置品牌信息
            Long brandId = skuEsModel.getBrandId();
            BrandEntity brand = brandService.getById(brandId);
            skuEsModel.setBrandName(brand.getName());
            skuEsModel.setBrandId(brand.getBrandId());

            // 设置分类信息
            Long catalogId = skuEsModel.getCatalogId();
            CategoryEntity category = categoryService.getById(catalogId);
            skuEsModel.setCatalogId(category.getCatId());
            skuEsModel.setCatalogName(category.getName());

            skuEsModel.setAttrs(attrsList);
            return esmode1;
        }).collect(Collectors.toList());

        // TODO 5. 将数据发送给es保存
        R r = searchFeignService.productStatusUp(upProducts);
        if (r.getCode() == 0) {
            // TODO 6. 修改当前spu的状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else{
            // 调用失败
            Exception exception = new Exception();
            exception.printStackTrace();
        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity byId = skuInfoService.getById(skuId);
        Long skuId1 = byId.getSkuId();
        SpuInfoEntity byId1 = getById(skuId1);
        return byId1;
    }

}